<template>
  <div class="product-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>商品管理</span>
          <el-button type="primary" @click="dialogVisible = true">上传商品</el-button>
        </div>
      </template>

      <!-- 商品展示 -->
      <div v-loading="loading">
        <el-empty v-if="products.length === 0" description="暂无商品" />
        <el-row :gutter="20" v-else>
          <el-col
            v-for="product in products"
            :key="product.id"
            :xs="12"
            :sm="8"
            :md="6"
            :lg="4"
            class="product-item"
          >
            <el-card :body-style="{ padding: '0px', cursor: 'pointer' }">
              <img
                :src="getImageUrl(product.path)"
                class="product-image"
                alt="商品图片"
                @error="handleImageError"
                @click="goToDetail(product.id)" 
              />
              <div style="padding: 14px">
                <span>{{ product.name }}</span>
                <div class="bottom">
                  <div class="price">¥{{ product.price?.toFixed(2) || '0.00' }}</div>
                  <time class="time">{{ formatDate(product.uploadTime) }}</time>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 上传对话框 -->
    <el-dialog v-model="dialogVisible" title="上传商品" width="30%">
      <el-form :model="productForm" label-width="80px">
        <el-form-item label="商品名称">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input-number v-model="productForm.price" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="productForm.overview" type="textarea" :rows="2" />
        </el-form-item>
        <el-upload
          class="upload-demo"
          drag
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :show-file-list="false"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">请上传图片文件，且不超过2MB</div>
          </template>
        </el-upload>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadProduct" :loading="uploading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { UploadFilled } from "@element-plus/icons-vue";
import api from "../../services/api";
import { ElMessage } from "element-plus";
import { ref, onMounted, reactive } from "vue";
import { useRouter } from 'vue-router';

const router = useRouter();
const uploading = ref(false);
const dialogVisible = ref(false);
const loading = ref(false);
const products = ref([]);
const productForm = reactive({
  name: '',
  price: 0,
  overview: '',
  file: null
});

const getImageUrl = (path) => {
  return `http://localhost:9000${path}`;
};

const handleImageError = (e) => {
  e.target.src = 'https://via.placeholder.com/300x300?text=Image+Not+Found';
};

const formatDate = (dateString) => {
  if (!dateString) return '未知时间';
  return dateString.split('T')[0];
};

const getProduct = async () => {
  try {
    loading.value = true;
    const response = await api.getProducts();
    products.value = response.data;
    console.log(products.value);
  } catch (error) {
    ElMessage.error('获取商品列表失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

const handleFileChange = (file) => {
  productForm.file = file.raw;
};

const uploadProduct = async () => {
  uploading.value = true;
  
  if (!productForm.file) {
    ElMessage.error('请选择文件');
    uploading.value = false;
    return;
  }

  if (!productForm.name.trim()) {
    ElMessage.error('请输入商品名称');
    uploading.value = false;
    return;
  }

  const formData = new FormData();
  formData.append('file', productForm.file);
  formData.append('name', productForm.name);
  formData.append('price', productForm.price);
  formData.append('overview', productForm.overview);

  try {
    await api.updataProduct(formData);
    ElMessage.success('商品上传成功');
    dialogVisible.value = false;
    productForm.name = '';
    productForm.price = 0;
    productForm.overview = '';
    productForm.file = null;
    await getProduct();
  } catch (error) {
    ElMessage.error('上传失败: ' + (error.response?.data?.message || error.message));
  } finally {
    uploading.value = false;
  }
};

const goToDetail = (productId) => {
  router.push(`/product/${productId}`);
};

onMounted(() => {
  getProduct();
  
});
</script>

<style scoped>
.product-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.product-item {
  margin-bottom: 20px;
}
.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  display: block;
}
.bottom {
  margin-top: 13px;
  line-height: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}
.price {
  color: #f56c6c;
  font-weight: bold;
}
.time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>